import React, {useState, useRef, useEffect} from 'react';
import {Edit3, Copy, X, GripVertical} from 'lucide-react';
import {useSortable} from '@dnd-kit/sortable';
import {CSS} from '@dnd-kit/utilities';
import {IconButton} from '@/components/ui/Button';
import {Modal} from '@/components/modals/Modal';
import {EditTabForm} from '@/components/forms/EditTabForm';
import {ConfirmPopover} from '@/components/ui/Popover';
import {Tooltip} from '@/components/ui/Tooltip';
import {useToast, useCopyTooltip, useFavicon} from '@/hooks/ui';
import {useUpdateTab, useDeleteTab} from '@/hooks/api/useTabs';
import {copyToClipboard, extractDomain, cn} from '@/lib/utils';
import type {TabItem} from '@/types';

interface EditFormData {
    title: string;
    url: string;
}

interface TabCardProps {
    tab: TabItem;
    collectionId: number;
    id: string;
    className?: string;
    disableSorting?: boolean;
    isAnyDragging?: boolean;
    isDragOverlay?: boolean;
    isSortingContainer?: boolean;
}

const TabCardComponent: React.FC<TabCardProps> = ({
    tab,
    collectionId,
    id,
    className,
    disableSorting = false,
    isAnyDragging = false,
    isDragOverlay = false,
    isSortingContainer = false,
}) => {
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isDeletePopoverOpen, setIsDeletePopoverOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const {
        tooltipContent: copyTooltipContent,
        isTooltipOpen: isCopyTooltipOpen,
        handleCopySuccess,
        handleMouseLeave: handleCopyMouseLeave,
        handleBlur: handleCopyBlur,
        handleTooltipOpenChange: handleCopyTooltipOpenChange,
    } = useCopyTooltip();

    const deleteButtonRef = useRef<HTMLDivElement>(null);

    // 使用 TanStack Query mutations
    const updateTabMutation = useUpdateTab();
    const deleteTabMutation = useDeleteTab();

    const toast = useToast();

    const {
        attributes,
        setNodeRef,
        listeners,
        isDragging,
        transform,
        transition,
    } = useSortable({
        id,
        data: {
            type: 'tab',
            collectionId,
        },
        disabled: disableSorting || isSortingContainer,
    });

    const style: React.CSSProperties = {};
    if (isDragOverlay) {
        style.transform = CSS.Transform.toString(transform);
        style.transition = transition;
    } else if (isDragging) {
        style.transform = undefined;
        style.transition = undefined;
    } else {
        style.transform = CSS.Transform.toString(transform);
        style.transition = transition;
    }

    const handleEditSubmit = async (formData: EditFormData) => {
        setIsSubmitting(true);
        try {
            await updateTabMutation.mutateAsync({
                tabId: tab.id,
                collectionId,
                data: {
                    title: formData.title.trim(),
                    url: formData.url.trim(),
                },
            });
            setIsEditModalOpen(false);
            toast.success('标签更新成功');
        } catch (error) {
            toast.error('更新失败，请重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleDeleteConfirm = async () => {
        setIsSubmitting(true);
        try {
            await deleteTabMutation.mutateAsync({
                tabId: tab.id,
                collectionId,
            });
            setIsDeletePopoverOpen(false);
            toast.success('标签页已删除');
        } catch (error) {
            toast.error('删除失败，请重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleCopyClick = async () => {
        const success = await copyToClipboard(tab.url);
        if (!success) return;
        handleCopySuccess();
    };

    const handleOpenLink = () => {
        window.open(tab.url, '_blank', 'noopener,noreferrer');
    };

    const imgRef = useRef<HTMLImageElement | null>(null);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        const el = imgRef.current;
        if (!el) return;
        const io = new IntersectionObserver(
            (entries) => {
                for (const entry of entries) {
                    if (entry.isIntersecting) {
                        setVisible(true);
                        io.disconnect();
                        break;
                    }
                }
            },
            {root: null, rootMargin: '200px', threshold: 0.01}
        );
        io.observe(el);
        return () => io.disconnect();
    }, [imgRef.current]);

    const faviconSrc = useFavicon(tab.url, tab.favicon, {enabled: visible});

    return (
        <>
            <div
                ref={isSortingContainer ? undefined : setNodeRef}
                style={style}
                {...attributes}
                className={cn(
                    'card link-card group',
                    'relative min-h-20 w-full px-4 py-3',
                    'cursor-pointer hover:shadow-card-hover',
                    'flex flex-col justify-between',
                    // 解释：被拖拽时的视觉反馈（半透明、轻微旋转、提高层级）
                    isDragging && 'opacity-50 transform rotate-2 z-50',
                    className
                )}
                // 解释：键盘可访问性；允许使用 Enter/Space 打开链接
                onKeyDown={(e) => {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        handleOpenLink();
                    }
                }}
                onClick={handleOpenLink}
            >
                {/* 解释：拖拽手柄，把 listeners 绑定在一个小区域，避免整张卡片都可被拖动 */}
                <Tooltip
                    content="拖拽"
                    side="top"
                    variant="drag"
                    // 解释：拖拽期间禁用 Tooltip 显示，避免拖拽时出现提示干扰
                    disabled={disableSorting || isDragging || isAnyDragging}
                >
                    <div
                        // 只有在手柄上拖动才会触发排序，降低误触
                        {...listeners}
                        className={cn(
                            'absolute -top-1.5 -left-1.5',
                            'w-5 h-5 bg-gray-600 text-white rounded-md shadow-sm',
                            'flex items-center justify-center cursor-grab active:cursor-grabbing',
                            'z-10',
                            // DragOverlay 专用逻辑：直接显示，不依赖其他状态
                            isDragOverlay ? [
                                'opacity-100 scale-100'
                            ] : [
                                // 搜索时强制隐藏（优先级最高）
                                disableSorting ? 'hidden' : [
                                    // 被拖拽的原始卡片：隐藏拖拽按钮（因为已经在拖拽中）
                                    isDragging ? 'opacity-0' : [
                                        // 正常卡片的逻辑
                                        'opacity-0 transition-all duration-200 transform-gpu',
                                        'hover:scale-110 transition-all',
                                        // 正常悬浮显示
                                        !isAnyDragging && 'group-hover:opacity-80 hover:opacity-100'
                                    ]
                                ]
                            ]
                        )}
                        // 解释：阻止事件冒泡，避免点击手柄触发卡片的"打开链接"逻辑
                        onClick={(e) => e.stopPropagation()}
                    >
                        <GripVertical className="w-2.5 h-2.5 flex-shrink-0"/>
                    </div>
                </Tooltip>

                {/* 删除按钮（右上角） */}
                <div ref={deleteButtonRef} className="absolute -top-2 -right-2">
                    <Tooltip content="删除" side="top" variant="delete">
                        <IconButton
                            variant="ghost"
                            size="icon"
                            onClick={(e) => {
                                e.stopPropagation();
                                setIsDeletePopoverOpen(true);
                            }}
                            className={cn(
                                'w-5 h-5 bg-white border border-gray-200 shadow-sm rounded-full',
                                'text-red-500 hover:text-white hover:bg-red-500 hover:border-red-500',
                                'z-10 transform-gpu',
                                'transition-all duration-300 ease-out',
                                // 初始状态：不可见，缩小到0.3倍
                                'opacity-0 scale-[0.3]',
                                // 气泡框打开时：显示并保持放大状态
                                isDeletePopoverOpen && 'opacity-100 scale-110',
                                // 非拖拽且非弹框状态下：group-hover显示，hover时放大
                                !isAnyDragging && !isDeletePopoverOpen && 'group-hover:opacity-100 group-hover:scale-100 hover:scale-110'
                            )}
                            icon={<X className="w-2.5 h-2.5 flex-shrink-0"/>}
                            aria-label="删除标签页"
                        />
                    </Tooltip>
                </div>

                {/* 卡片头部：图标 + 标题 */}
                <div className="flex items-center gap-3.5 flex-1 my-1">
                    {/* 网站图标 */}
                    <img
                        ref={imgRef}
                        src={faviconSrc}
                        alt=""
                        className="link-favicon w-6 h-6 rounded-sm object-contain flex-shrink-0"
                        loading="lazy"
                        decoding="async"
                    />

                    {/* 标题内容 */}
                    <div className="flex-1 min-w-0">
                        <h4
                            className="text-sm font-medium text-gray-900 line-clamp-2 leading-snug"
                            title={tab.title}
                        >
                            {tab.title}
                        </h4>
                    </div>
                </div>

                {/* 分隔线 */}
                <div className="border-t border-gray-200 mt-2 mb-2"/>

                {/* 卡片底部：描述或域名 */}
                <div className="min-h-5 mb-1">
                    <p className="text-sm text-gray-500 line-clamp-1" title={tab.url}>
                        {extractDomain(tab.url)}
                    </p>
                </div>

                {/* 右下角按钮组 */}
                <div className={cn(
                    'absolute -bottom-2 -right-2',
                    'flex gap-1.5',
                    'transform-gpu origin-center-right',
                    // 初始隐藏：禁用指针事件，防止提前触发 Tooltip
                    'opacity-0 scale-[0.3] translate-x-2 pointer-events-none',
                    'transition-all duration-300 ease-out',
                    // 显示状态：启用 pointer-events
                    isDeletePopoverOpen && 'opacity-100 scale-100 translate-x-0 pointer-events-auto',
                    !isAnyDragging && !isDeletePopoverOpen && 'group-hover:opacity-100 group-hover:scale-100 group-hover:translate-x-0 group-hover:pointer-events-auto'
                )}>
                    {/* 编辑按钮 */}
                    <Tooltip content="编辑" side="bottom" variant="edit">
                        <IconButton
                            variant="ghost"
                            size="icon"
                            onClick={(e) => {
                                e.stopPropagation();
                                setIsEditModalOpen(true);
                            }}
                            className={cn(
                                'w-6 h-6 bg-gray-700 text-white shadow-sm rounded-full',
                                'hover:bg-primary-600 hover:scale-110 transition-all'
                            )}
                            icon={<Edit3 className="w-2.5 h-2.5 flex-shrink-0"/>}
                            aria-label="编辑标签页"
                        />
                    </Tooltip>

                    {/* 复制按钮 */}
                    <Tooltip
                        content={copyTooltipContent}
                        side="bottom"
                        variant="copy"
                        open={isCopyTooltipOpen}
                        onOpenChange={handleCopyTooltipOpenChange}
                    >
                        <IconButton
                            variant="ghost"
                            size="icon"
                            onClick={(e) => {
                                e.stopPropagation();
                                void handleCopyClick();
                            }}
                            onMouseLeave={handleCopyMouseLeave}
                            onBlur={handleCopyBlur}
                            className={cn(
                                'w-6 h-6 bg-gray-700 text-white shadow-sm rounded-full',
                                'hover:bg-success-600 hover:scale-110 transition-all'
                            )}
                            icon={<Copy className="w-2.5 h-2.5 flex-shrink-0"/>}
                            aria-label="复制"
                        />
                    </Tooltip>
                </div>
            </div>

            <Modal
                open={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                title="编辑标签页"
                size="md"
                closeOnBackdrop={false}
                footer={(
                    <div className="flex justify-end gap-3">
                        <button
                            type="button"
                            onClick={() => setIsEditModalOpen(false)}
                            className="btn-secondary"
                            disabled={isSubmitting}
                        >
                            取消
                        </button>
                        <button
                            type="reset"
                            form="edit-tab-form"
                            className="btn-reset"
                            disabled={isSubmitting}
                        >
                            重置
                        </button>
                        <button
                            type="submit"
                            form="edit-tab-form"
                            className="btn-primary"
                            disabled={isSubmitting}
                        >
                            {isSubmitting ? '保存中…' : '保存'}
                        </button>
                    </div>
                )}
            >
                <EditTabForm
                    initialData={{
                        title: tab.title,
                        url: tab.url,
                    }}
                    loading={isSubmitting}
                    onSubmit={handleEditSubmit}
                />
            </Modal>

            <ConfirmPopover
                triggerRef={deleteButtonRef}
                open={isDeletePopoverOpen}
                onClose={() => setIsDeletePopoverOpen(false)}
                onConfirm={handleDeleteConfirm}
                confirmText="删除"
                cancelText="取消"
                confirmVariant="danger"
                loading={isSubmitting}
            />
        </>
    );
};

export const TabCard = React.memo(TabCardComponent);
